package com.evendai.sipdemo.util

import android.content.Context
import android.graphics.PixelFormat
import android.os.Build
import android.view.Gravity
import android.view.View
import android.view.WindowManager
import com.evendai.sipdemo.App
import com.evendai.sipdemo.sip.listener.FloatViewOnTouchListener

class FloatViewUtil {

    companion object {

        @Suppress("DEPRECATION")
        fun showFloatView(floatView: View) {
            val floatViewType = when {
                Build.VERSION.SDK_INT >= Build.VERSION_CODES.O -> WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
                Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1 -> WindowManager.LayoutParams.TYPE_PHONE
                else -> WindowManager.LayoutParams.TYPE_TOAST
            }

            val windowManager = App.getContext().getSystemService(Context.WINDOW_SERVICE) as WindowManager
            val params = WindowManager.LayoutParams().apply {
                type = floatViewType
                flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE // 不设置这个flag的话，屏幕上任何内容都没法接收触摸事件了
                width = WindowManager.LayoutParams.WRAP_CONTENT
                height = WindowManager.LayoutParams.WRAP_CONTENT
                gravity = (Gravity.START or Gravity.TOP)
                format = PixelFormat.TRANSLUCENT
            }
            floatView.setOnTouchListener(FloatViewOnTouchListener(params, windowManager))
            windowManager.addView(floatView, params)
        }

        fun hideFloatView(floatView: View) {
            (App.getContext().getSystemService(Context.WINDOW_SERVICE) as WindowManager).removeView(floatView)
        }

    }

}